﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using DevExpress.Utils;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using WindowsForms.AOnline.Model.BusinessObjects.Dictionary;
using WindowsForms.AOnline.Presenter.Dictionary.Account;
using WindowsForms.AOnline.Presenter.Dictionary.Department;
using WindowsForms.AOnline.Presenter.Dictionary.FixedAsset;
using WindowsForms.AOnline.Presenter.Dictionary.FixedAssetCategory;
using WindowsForms.AOnline.Session;
using WindowsForms.AOnline.View.Dictionary;
using WindowsForms.AOnline.WindowsForm.FormBase;
using WindowsForms.AOnline.WindowsForm.FormBase.PropertyGrid;
using WindowsForms.AOnline.WindowsForm.Resources;

namespace WindowsForms.AOnline.WindowsForm.FormDictionary
{
    public partial class FrmXtraFixedAssetDetail : FrmXtraBaseCategoryDetail, IFixedAssetView, IFixedAssetCategorysView, IDepartmentsView, IAccountsView
    {
        private readonly FixedAssetPresenter _fixedAssetPresenter;
        private readonly FixedAssetCategorysPresenter _fixedAssetCategoriesPresenter;
        private readonly DepartmentsPresenter _departmentsPresenter;
        private readonly AccountsPresenter _accountsPresenter;
        //private readonly EmployeesPresenter _employeesPresenter;
        public FrmXtraFixedAssetDetail()
        {
            InitializeComponent();
            _fixedAssetPresenter = new FixedAssetPresenter(this);
            _fixedAssetCategoriesPresenter = new FixedAssetCategorysPresenter(this);
            _departmentsPresenter = new DepartmentsPresenter(this);
            _accountsPresenter = new AccountsPresenter(this);
            //_employeesPresenter = new EmployeesPresenter(this);
        }

        #region Override Methods

        /// <summary>
        /// Initializes the data.
        /// </summary>
        protected override void InitData()
        {
            _fixedAssetCategoriesPresenter.GetAll();
            _departmentsPresenter.GetAll();
            _accountsPresenter.GetAll();

            if (ActionMode == ActionModeEnum.AddNew)
            {
                cboState.SelectedIndex = 1;
            }
            if (KeyValue != null)
                _fixedAssetPresenter.Display(KeyValue);
        }
        /// <summary>
        /// Valids the data.
        /// </summary>
        /// <returns></returns>
        protected override bool ValidData()
        {
            if (string.IsNullOrEmpty(FixedAssetCode))
            {
                XtraMessageBox.Show(ResourceHelper.GetResourceValueByName("ResEmptyFixedAssetCode"),
                                ResourceHelper.GetResourceValueByName("ResDetailContent"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtFixedAssetCode.Focus();
                return false;
            }
            if (string.IsNullOrEmpty(FixedAssetName))
            {
                XtraMessageBox.Show(ResourceHelper.GetResourceValueByName("ResEmptyFixedAssetName"),
                                ResourceHelper.GetResourceValueByName("ResDetailContent"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtFixedAssetName.Focus();
                return false;
            }
            if (ReferenceEquals(grdLookUpFixedAssetCategory.EditValue, "") || ReferenceEquals(grdLookUpFixedAssetCategory.EditValue, null))
            {
                XtraMessageBox.Show(ResourceHelper.GetResourceValueByName("ResEmptyFixedAssetCategoryID"),
                                ResourceHelper.GetResourceValueByName("ResDetailContent"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                grdLookUpFixedAssetCategory.Focus();
                return false;
            }
            if (ReferenceEquals(cboState.EditValue, "") || ReferenceEquals(cboState.EditValue, null))
            {
                XtraMessageBox.Show(ResourceHelper.GetResourceValueByName("ResEmptyFixedAssetState"),
                                ResourceHelper.GetResourceValueByName("ResDetailContent"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                cboState.Focus();
                return false;
            }
            //if (ReferenceEquals(grdLookUpDepartment.EditValue, null) || ReferenceEquals(grdLookUpDepartment.EditValue, ""))
            //{
            //    XtraMessageBox.Show(ResourceHelper.GetResourceValueByName("ResEmptyDepartmentID"),
            //                    ResourceHelper.GetResourceValueByName("ResDetailContent"), MessageBoxButtons.OK, MessageBoxIcon.Error);
            //    tabControl.SelectedTabPage = tabGeneralInfo;
            //    grdLookUpDepartment.Focus();
            //    return false;
            //}
            if (ReferenceEquals(dtPurchasedDate.EditValue, null))
            {
                XtraMessageBox.Show(ResourceHelper.GetResourceValueByName("ResEmptyPurchasedDate"),
                                ResourceHelper.GetResourceValueByName("ResDetailContent"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                tabControl.SelectedTabPage = tabAmountInfo;
                dtPurchasedDate.Focus();
                return false;
            }
            if (ReferenceEquals(dtUsedDate.EditValue, null))
            {
                XtraMessageBox.Show(ResourceHelper.GetResourceValueByName("ResEmptyUsedDate"),
                                ResourceHelper.GetResourceValueByName("ResDetailContent"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                tabControl.SelectedTabPage = tabAmountInfo;
                dtUsedDate.Focus();
                return false;
            }
            if (ReferenceEquals(dtDepreciationDate.EditValue, null))
            {
                XtraMessageBox.Show(ResourceHelper.GetResourceValueByName("ResEmptyDepreciationDate"),
                                ResourceHelper.GetResourceValueByName("ResDetailContent"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                tabControl.SelectedTabPage = tabAmountInfo;
                dtDepreciationDate.Focus();
                return false;
            }
            if (string.IsNullOrEmpty(OrgPriceAccountCode))
            {
                XtraMessageBox.Show(ResourceHelper.GetResourceValueByName("ResEmptyOrgPriceAccount"),
                                ResourceHelper.GetResourceValueByName("ResDetailContent"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                tabControl.SelectedTabPage = tabAmountInfo;
                grdLookUpOrgPriceAccount.Focus();
                return false;
            }
            if (string.IsNullOrEmpty(CapitalAccountCode))
            {
                XtraMessageBox.Show(ResourceHelper.GetResourceValueByName("ResEmptyCapitalAccount"),
                                ResourceHelper.GetResourceValueByName("ResDetailContent"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                tabControl.SelectedTabPage = tabAmountInfo;
                grdLookUpCapitalAccount.Focus();
                return false;
            }
            if (string.IsNullOrEmpty(DepreciationAccountCode))
            {
                XtraMessageBox.Show(ResourceHelper.GetResourceValueByName("ResEmptyDepreciationAccount"),
                                ResourceHelper.GetResourceValueByName("ResDetailContent"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                tabControl.SelectedTabPage = tabAmountInfo;
                grdLookUpDepreciationAccount.Focus();
                return false;
            }
            if (LifeTime == 0)
            {
                XtraMessageBox.Show(ResourceHelper.GetResourceValueByName("ResEmptyLifeTime"),
                                ResourceHelper.GetResourceValueByName("ResDetailContent"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                tabControl.SelectedTabPage = tabAmountInfo;
                txtLifeTime.Focus();
                return false;
            }
            if (DepreciationRate == 0)
            {
                XtraMessageBox.Show(ResourceHelper.GetResourceValueByName("ResEmptyDepreciationRate"),
                                ResourceHelper.GetResourceValueByName("ResDetailContent"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                tabControl.SelectedTabPage = tabAmountInfo;
                txtDepreciationRate.Focus();
                return false;
            }
            if (txtQuantity.Value <= 0)
            {
                XtraMessageBox.Show(ResourceHelper.GetResourceValueByName("ResFixedAssetQuantityNotValid"),
                                ResourceHelper.GetResourceValueByName("ResDetailContent"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                tabControl.SelectedTabPage = tabAmountInfo;
                txtQuantity.Focus();
                return false;
            }

            return true;
        }

        /// <summary>
        /// Saves the data.
        /// </summary>
        /// <returns></returns>
        protected override string SaveData()
        {
            //string i;
            //try
            //{
            return _fixedAssetPresenter.Save();
            //    if (i > 1)
            //    {
            //        PostToOpenningFixedAsset();
            //        PostToGL();
            //    }
            //}
            //catch (Exception ex)
            //{
            //    i = 0;
            //    if (ex.Message.Contains("IX_FixedAsset_FixedAssetCode"))
            //    {
            //        XtraMessageBox.Show(string.Format(ResourceHelper.GetResourceValueByName("ResFixedAssetAlreadyExists"), FixedAssetCode), ResourceHelper.GetResourceValueByName("ResDetailContent"), MessageBoxButtons.OK, MessageBoxIcon.Error);
            //        txtFixedAssetCode.Focus();
            //    }
            //    else
            //    {
            //        XtraMessageBox.Show(ex.Message, ResourceHelper.GetResourceValueByName("ResDetailContent"), MessageBoxButtons.OK, MessageBoxIcon.Error);
            //    }
            //}

            //return i;

        }


        /// <summary>
        /// Focuses the control.
        /// </summary>
        protected override void InitControls()
        {
            txtFixedAssetCode.Focus();
        }

        #endregion

        #region Calculate Amount

        /// <summary>
        /// Calculates the depreciation.
        /// </summary>
        /// <param name="startDateTimeDb">The start date time database.</param>
        private void CalculateDepreciation(DateTime startDateTimeDb)
        {
            try
            {
                var depreciationMonth = dtDepreciationDate.DateTime.Month;
                var depreciationYear = dtDepreciationDate.DateTime.Year;
                var ogrPrice = txtOrgPrice.Value;
                var depreciationRate = txtDepreciationRate.Value;

                var usingYear = startDateTimeDb.Year - depreciationYear;
                var usingMonth = (12 - (depreciationMonth - 1)) + (usingYear - 1) * 12;

                decimal accumDepreciationAmount;
                decimal remainingAmount;
                if (usingYear <= 0)
                {
                    accumDepreciationAmount = 0;
                    remainingAmount = ogrPrice;
                }
                else
                {
                    if (usingYear >= txtLifeTime.Value)
                    {
                        accumDepreciationAmount = ogrPrice;
                        remainingAmount = 0;
                    }
                    else
                    {
                        accumDepreciationAmount = Math.Round((ogrPrice * depreciationRate / 100) / 12 * usingMonth, 2);
                        remainingAmount = ogrPrice - accumDepreciationAmount;
                    }
                }
                txtAccumDepreciationAmount.Value = accumDepreciationAmount;
                txtRemainingAmount.Value = remainingAmount;
                txtAnnualDepreciationAmount.Value = Math.Round((ogrPrice * depreciationRate / 100), 2);
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message, "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// Calculates the org price.
        /// </summary>
        private void CalculateOrgPrice()
        {
            try
            {
                txtOrgPrice.Value = txtUnitPrice.Value * txtQuantity.Value;
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message, "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }


        /// <summary>
        /// Posts to openning fixed asset.
        /// </summary>
        private void PostToOpenningFixedAsset()
        {

        }

        /// <summary>
        /// Posts to gl.
        /// </summary>
        private void PostToGL()
        {

        }

        #endregion
        // Tuấn HM

        #region IFixedAssetView Members

        /// <summary>
        /// Gets or sets the fixed asset identifier.
        /// </summary>
        /// <value>
        /// The fixed asset identifier.
        /// </value>
        public long FixedAssetId { get; set; }

        /// <summary>
        /// Gets or sets the fixed asset code.
        /// </summary>
        /// <value>
        /// The fixed asset code.
        /// </value>
        public string FixedAssetCode
        {
            get { return txtFixedAssetCode.Text; }
            set { txtFixedAssetCode.Text = value; }
        }

        /// <summary>
        /// Gets or sets the name of the fixed asset.
        /// </summary>
        /// <value>
        /// The name of the fixed asset.
        /// </value>
        public string FixedAssetName
        {
            get { return txtFixedAssetName.Text; }
            set { txtFixedAssetName.Text = value; }
        }

        /// <summary>
        /// Gets or sets the fixed asset name en.
        /// </summary>
        /// <value>
        /// The fixed asset name en.
        /// </value>
        public string FixedAssetForeignName { get; set; }

        /// <summary>
        /// Gets or sets the fixed asset category identifier.
        /// </summary>
        /// <value>
        /// The fixed asset category identifier.
        /// </value>
        public int FixedAssetCategoryId
        {
            get
            {
                if (grdLookUpFixedAssetCategory.EditValue == null) return 0;
                return (int)grdLookUpFixedAssetCategory.EditValue;
            }
            set
            {
                grdLookUpFixedAssetCategory.EditValue = value;
            }
        }

        /// <summary>
        /// Gets or sets the state.
        /// </summary>
        /// <value>
        /// The state.
        /// </value>
        public int State
        {
            get { return cboState.SelectedIndex; }
            set { cboState.SelectedIndex = value; }
        }

        /// <summary>
        /// Gets or sets the description.
        /// </summary>
        /// <value>
        /// The description.
        /// </value>
        public string Description
        {
            get { return txtDescription.Text; }
            set { txtDescription.Text = value; }
        }

        /// <summary>
        /// Gets or sets the production year.
        /// </summary>
        /// <value>
        /// The production year.
        /// </value>
        public int ProductionYear
        {
            get { return (int)txtProductYear.Value; }
            set { txtProductYear.Value = value; }
        }

        /// <summary>
        /// Gets or sets the made in.
        /// </summary>
        /// <value>
        /// The made in.
        /// </value>
        public string MadeIn
        {
            get { return txtMadeIn.Text; }
            set { txtMadeIn.Text = value; }
        }

        /// <summary>
        /// Gets or sets the purchased date.
        /// </summary>
        /// <value>
        /// The purchased date.
        /// </value>
        public DateTime PurchasedDate
        {
            get { return dtPurchasedDate.DateTime; }
            set { dtPurchasedDate.DateTime = value; }
        }

        /// <summary>
        /// Gets or sets the used date.
        /// </summary>
        /// <value>
        /// The used date.
        /// </value>
        public DateTime UsedDate
        {
            get { return dtUsedDate.DateTime; }
            set { dtUsedDate.DateTime = value; }
        }

        /// <summary>
        /// Gets or sets the depreciation date.
        /// </summary>
        /// <value>
        /// The depreciation date.
        /// </value>
        public DateTime DepreciationDate
        {
            get { return dtDepreciationDate.DateTime; }
            set { dtDepreciationDate.DateTime = value; }
        }

        /// <summary>
        /// Gets or sets the increment date.
        /// </summary>
        /// <value>
        /// The increment date.
        /// </value>
        public DateTime IncrementDate { get { return DateTime.Now; } set { } }

        /// <summary>
        /// Gets or sets the disposed date.
        /// </summary>
        /// <value>
        /// The disposed date.
        /// </value>
        public DateTime DisposedDate { get { return DateTime.Now; } set { } }

        /// <summary>
        /// Gets or sets the unit.
        /// </summary>
        /// <value>
        /// The unit.
        /// </value>
        public string Unit
        {
            get { return txtUnit.Text; }
            set { txtUnit.Text = value; }
        }

        /// <summary>
        /// Gets or sets the serial number.
        /// </summary>
        /// <value>
        /// The serial number.
        /// </value>
        public string SerialNumber
        {
            get { return txtSerialNumber.Text; }
            set { txtSerialNumber.Text = value; }
        }

        /// <summary>
        /// Gets or sets the accessories.
        /// </summary>
        /// <value>
        /// The accessories.
        /// </value>
        public string Accessories
        {
            get { return txtAccessories.Text; }
            set { txtAccessories.Text = value; }
        }

        /// <summary>
        /// Gets or sets the quantity.
        /// </summary>
        /// <value>
        /// The quantity.
        /// </value>
        public int Quantity
        {
            get { return (int)txtQuantity.Value; }
            set { txtQuantity.Value = value; }
        }

        /// <summary>
        /// Gets or sets the unit price.
        /// </summary>
        /// <value>
        /// The unit price.
        /// </value>
        public decimal UnitPrice
        {
            get { return txtUnitPrice.Value; }
            set { txtUnitPrice.Value = value; }
        }

        /// <summary>
        /// Gets or sets the org price.
        /// </summary>
        /// <value>
        /// The org price.
        /// </value>
        public decimal OrgPrice
        {
            get { return txtOrgPrice.Value; }
            set { txtOrgPrice.Value = value; }
        }

        /// <summary>
        /// Gets or sets the accum depreciation amount.
        /// </summary>
        /// <value>
        /// The accum depreciation amount.
        /// </value>
        public decimal AccumDepreciationAmount
        {
            get { return txtAccumDepreciationAmount.Value; }
            set { txtAccumDepreciationAmount.Value = value; }
        }

        /// <summary>
        /// Gets or sets the remaining amount.
        /// </summary>
        /// <value>
        /// The remaining amount.
        /// </value>
        public decimal RemainingAmount
        {
            get { return txtRemainingAmount.Value; }
            set { txtRemainingAmount.Value = value; }
        }


        /// <summary>
        /// Gets or sets the annual depreciation amount.
        /// </summary>
        /// <value>
        /// The annual depreciation amount.
        /// </value>
        public decimal AnnualDepreciationAmount
        {
            get { return txtAnnualDepreciationAmount.Value; }
            set { txtAnnualDepreciationAmount.Value = value; }
        }


        /// <summary>
        /// Gets or sets the life time.
        /// </summary>
        /// <value>
        /// The life time.
        /// </value>
        public decimal LifeTime
        {
            get { return txtLifeTime.Value; }
            set { txtLifeTime.Value = value; }
        }

        /// <summary>
        /// Gets or sets the depreciation rate.
        /// </summary>
        /// <value>
        /// The depreciation rate.
        /// </value>
        public decimal DepreciationRate
        {
            get { return txtDepreciationRate.Value; }
            set { txtDepreciationRate.Value = value; }
        }

        /// <summary>
        /// Gets or sets the org price account.
        /// </summary>
        /// <value>
        /// The org price account.
        /// </value>
        public string OrgPriceAccountCode
        {
            get
            {
                if (grdLookUpOrgPriceAccount.EditValue == null) return null;
                return (string)grdLookUpOrgPriceAccount.GetColumnValue("AccountCode");
            }
            set
            {
                grdLookUpOrgPriceAccount.EditValue = value;
            }
        }

        /// <summary>
        /// Gets or sets the depreciation account.
        /// </summary>
        /// <value>
        /// The depreciation account.
        /// </value>
        public string DepreciationAccountCode
        {
            get
            {
                if (grdLookUpDepreciationAccount.EditValue == null) return null;
                return (string)grdLookUpDepreciationAccount.GetColumnValue("AccountCode");
            }
            set
            {
                grdLookUpDepreciationAccount.EditValue = value;
            }
        }

        /// <summary>
        /// Gets or sets the capital account.
        /// </summary>
        /// <value>
        /// The capital account.
        /// </value>
        public string CapitalAccountCode
        {
            get
            {
                if (grdLookUpCapitalAccount.EditValue == null) return null;
                return (string)grdLookUpCapitalAccount.GetColumnValue("AccountCode");
            }
            set
            {
                grdLookUpCapitalAccount.EditValue = value;
            }
        }

        public string ExpenseAccountCode { get; set; }

        public string CapitalMoneyAccountCode { get; set; }

        /// <summary>
        /// Gets or sets the department identifier.
        /// </summary>
        /// <value>
        /// The department identifier.
        /// </value>
        public int DepartmentId
        {
            get
            {
                if (grdLookUpDepartment.EditValue == null) return 0;
                return (int)grdLookUpDepartment.GetColumnValue("DepartmentId");
            }
            set
            {
                grdLookUpDepartment.EditValue = value;
                //_departmentsPresenter.DisplayByDepartment(value);
            }
        }

        /// <summary>
        /// Gets or sets the employee identifier.
        /// </summary>
        /// <value>
        /// The employee identifier.
        /// </value>
        public long EmployeeId{ get; set; }

        /// <summary>
        /// Gets or sets a value indicating whether [is active].
        /// </summary>
        /// <value>
        ///   <c>true</c> if [is active]; otherwise, <c>false</c>.
        /// </value>
        public bool IsActive
        {
            get { return chkInactive.Checked; }
            set { chkInactive.Checked = value; }
        }

        public long UnitId { get; set; }

        #endregion

        #region IAccountsView Members

        /// <summary>
        /// Sets the accounts.
        /// </summary>
        /// <value>
        /// The accounts.
        /// </value>
        public IList<AccountModel> Accounts
        {
            set
            {
                var capitalAccountList = value.Where(c => c.AccountCode.StartsWith("421")).ToList();
                grdLookUpCapitalAccount.Properties.DataSource = capitalAccountList;
                grdLookUpCapitalAccount.Properties.ForceInitialize();
                grdLookUpCapitalAccount.Properties.PopulateColumns();

                var depreciationAccountList = value.Where(c => c.AccountCode.StartsWith("214")).ToList();
                grdLookUpDepreciationAccount.Properties.DataSource = depreciationAccountList;
                grdLookUpDepreciationAccount.Properties.ForceInitialize();
                grdLookUpDepreciationAccount.Properties.PopulateColumns();

                var orgPriceAccountList = value.Where(c => c.AccountCode.StartsWith("211")).ToList();
                grdLookUpOrgPriceAccount.Properties.DataSource = orgPriceAccountList;
                grdLookUpOrgPriceAccount.Properties.ForceInitialize();
                grdLookUpOrgPriceAccount.Properties.PopulateColumns();

                var treeColumnsCollection = new List<XtraColumn>
                                            {
                                                new XtraColumn{ColumnName = "AccountId", ColumnCaption = "", ColumnVisible = false},
                                                  new XtraColumn{ColumnName = "UnitId", ColumnCaption = "", ColumnVisible = false                                                },new XtraColumn{ColumnName = "AccountCode", ColumnPosition = 1, ColumnCaption = "Mã tài khoản", ColumnVisible = true },
                                                 new XtraColumn{ColumnName = "AccountName", ColumnPosition = 2, ColumnCaption = "Tên tài khoản", ColumnVisible = true },
                                                 new XtraColumn{ColumnName = "ParentId", ColumnCaption = "", ColumnVisible = false},
                                                 new XtraColumn{ColumnName = "Grade", ColumnCaption = "", ColumnVisible = false},
                                                 new XtraColumn{ColumnName = "IsDetail", ColumnCaption = "", ColumnVisible = false},
                                                 new XtraColumn{ColumnName = "Description", ColumnCaption = "", ColumnVisible = false},
                                                new XtraColumn{ColumnName = "BalanceSide", ColumnCaption = "", ColumnVisible = false},
                                                 new XtraColumn{ColumnName = "IsCustomer", ColumnCaption = "", ColumnVisible = false},
                                                 new XtraColumn{ColumnName = "IsVendor", ColumnCaption = "", ColumnVisible = false},
                                                 new XtraColumn{ColumnName = "IsInventoryItem", ColumnCaption = "", ColumnVisible = false},
                                                  new XtraColumn{ColumnName = "IsFixedAsset", ColumnCaption = "", ColumnVisible = false},                                              
                                                 new XtraColumn{ColumnName = "IsSystem", ColumnCaption = "", ColumnVisible = false},
                                                 new XtraColumn{ColumnName = "IsTax", ColumnCaption = "", ColumnVisible = false},
                                                new XtraColumn{ColumnName = "IsActive",   ColumnPosition = 3,ColumnCaption = "Được sử dụng",  ColumnVisible = false}
                                            };

                foreach (var column in treeColumnsCollection)
                {
                    if (column.ColumnVisible)
                    {
                        grdLookUpCapitalAccount.Properties.Columns[column.ColumnName].Caption = column.ColumnCaption;
                        grdLookUpCapitalAccount.Properties.SortColumnIndex = column.ColumnPosition;

                        grdLookUpDepreciationAccount.Properties.Columns[column.ColumnName].Caption = column.ColumnCaption;
                        grdLookUpDepreciationAccount.Properties.SortColumnIndex = column.ColumnPosition;

                        grdLookUpOrgPriceAccount.Properties.Columns[column.ColumnName].Caption = column.ColumnCaption;
                        grdLookUpOrgPriceAccount.Properties.SortColumnIndex = column.ColumnPosition;
                    }
                    else
                    {
                        grdLookUpCapitalAccount.Properties.Columns[column.ColumnName].Visible = false;
                        grdLookUpDepreciationAccount.Properties.Columns[column.ColumnName].Visible = false;
                        grdLookUpOrgPriceAccount.Properties.Columns[column.ColumnName].Visible = false;
                    }

                }
                grdLookUpCapitalAccount.Properties.DisplayMember = "AccountCode";
                grdLookUpCapitalAccount.Properties.ValueMember = "AccountCode";

                grdLookUpDepreciationAccount.Properties.DisplayMember = "AccountCode";
                grdLookUpDepreciationAccount.Properties.ValueMember = "AccountCode";

                grdLookUpOrgPriceAccount.Properties.DisplayMember = "AccountCode";
                grdLookUpOrgPriceAccount.Properties.ValueMember = "AccountCode";

            }
        }

        #endregion

        #region IDepartmentsView Members

        /// <summary>
        /// Sets the departments.
        /// </summary>
        /// <value>
        /// The departments.
        /// </value>
        public IList<DepartmentModel> Departments
        {
            set
            {
                grdLookUpDepartment.Properties.DataSource = value;
                grdLookUpDepartment.Properties.PopulateColumns();

                var treeColumnsCollection = new List<XtraColumn> { 
                                                new XtraColumn { ColumnName = "DepartmentId", ColumnVisible = false },
                                                new XtraColumn { ColumnName = "ParentId", ColumnVisible = false },
                                                new XtraColumn { ColumnName = "Code", ColumnCaption = "Mã phòng ban", ColumnPosition = 1, ColumnVisible = true },
                                                new XtraColumn { ColumnName = "Name", ColumnCaption = "Tên phòng ban", ColumnPosition = 2, ColumnVisible = true },
                                                new XtraColumn { ColumnName = "UnitId", ColumnVisible = false },
                                                new XtraColumn { ColumnName = "Address", ColumnVisible = false },
                                                new XtraColumn { ColumnName = "PhoneNumber", ColumnVisible = false },
                                                new XtraColumn { ColumnName = "Fax", ColumnVisible = false },
                                                new XtraColumn { ColumnName = "Description", ColumnVisible = false },
                                                new XtraColumn { ColumnName = "IsActive", ColumnVisible = false }                                           };

                foreach (var column in treeColumnsCollection)
                {
                    if (column.ColumnVisible)
                    {
                        grdLookUpDepartment.Properties.Columns[column.ColumnName].Caption = column.ColumnCaption;
                        grdLookUpDepartment.Properties.SortColumnIndex = column.ColumnPosition;
                    }
                    else grdLookUpDepartment.Properties.Columns[column.ColumnName].Visible = false;
                }
                grdLookUpDepartment.Properties.DisplayMember = "Name";
                grdLookUpDepartment.Properties.ValueMember = "DepartmentId";
            }
        }

        #endregion

        #region IFixedAssetCategorysView Members

        /// <summary>
        /// Sets the fixed asset categorys.
        /// </summary>
        /// <value>
        /// The fixed asset categorys.
        /// </value>
        public IList<FixedAssetCategoryModel> FixedAssetCategorys
        {
            set
            {
                grdLookUpFixedAssetCategory.Properties.DataSource = value;
                grdLookUpFixedAssetCategoryView.PopulateColumns(value);
                var treeColumnsCollection = new List<XtraColumn>
                                            {
                                                new XtraColumn
                                                {
                                                    ColumnName = "FixedAssetCategoryId",
                                                    ColumnCaption = "Mã loại TS",
                                                    ColumnVisible = false,
                                                    ColumnWith = 100
                                                },
                                                new XtraColumn
                                                {
                                                    ColumnName = "ParentId",
                                                    ColumnCaption = "Tài khoản cha",
                                                    ColumnVisible = false
                                                },
                                                new XtraColumn
                                                {
                                                    ColumnName = "FixedAssetCategoryCode",
                                                    ColumnCaption = "Mã loại TS",
                                                    ColumnPosition = 1,
                                                    ColumnVisible = true
                                                },
                                                new XtraColumn
                                                {
                                                    ColumnName = "FixedAssetCategoryName",
                                                    ColumnCaption = "Tên loại TS",
                                                    ColumnPosition = 2,
                                                    ColumnVisible = true
                                                },
                                                new XtraColumn
                                                {
                                                    ColumnName = "IsActive",
                                                    ColumnCaption = "Ngừng sử dụng",
                                                    ColumnVisible = false
                                                },
                                                new XtraColumn
                                                {
                                                    ColumnName = "LifeTime",
                                                    ColumnPosition = 3,
                                                    ColumnCaption = "Thời gian sử dụng",
                                                    ColumnWith = 100,
                                                    ColumnVisible = true
                                                },
                                                new XtraColumn
                                                {
                                                    ColumnName = "DepreciationRate",
                                                    ColumnPosition = 4,
                                                    ColumnCaption = "Tỷ lệ khấu hao",
                                                    ColumnWith = 100,
                                                    ColumnVisible = true
                                                },
                                                new XtraColumn { ColumnName = "Grade", ColumnVisible = false },
                                                new XtraColumn { ColumnName = "IsParent", ColumnVisible = false },
                                                new XtraColumn { ColumnName = "OrgPriceAccountCode", ColumnVisible = false},
                                                new XtraColumn { ColumnName = "DepreciationAccountCode", ColumnVisible = false },
                                                new XtraColumn { ColumnName = "OrgPriceAccountCode", ColumnVisible = false },
                                                new XtraColumn { ColumnName = "CapitalAccountCode", ColumnVisible = false },
                                                 new XtraColumn { ColumnName = "UnitId", ColumnVisible = false }
                                            };

                foreach (var column in treeColumnsCollection)
                {
                    if (column.ColumnVisible)
                    {
                        grdLookUpFixedAssetCategoryView.Columns[column.ColumnName].Caption = column.ColumnCaption;
                        grdLookUpFixedAssetCategoryView.Columns[column.ColumnName].SortIndex = column.ColumnPosition;
                    }
                    else grdLookUpFixedAssetCategoryView.Columns[column.ColumnName].Visible = false;
                }
                grdLookUpFixedAssetCategory.Properties.DisplayMember = "FixedAssetCategoryName";
                grdLookUpFixedAssetCategory.Properties.ValueMember = "FixedAssetCategoryId";
            }
        }

        #endregion

        #region Events

        /// <summary>
        /// Handles the EditValueChanged event of the txtDepreciationRate control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        private void txtDepreciationRate_EditValueChanged(object sender, EventArgs e)
        {
            CalculateDepreciation(Convert.ToDateTime(GlobalVariable.StartedDate));
        }

        /// <summary>
        /// Handles the EditValueChanged event of the txtLifeTime control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        private void txtLifeTime_EditValueChanged(object sender, EventArgs e)
        {
            CalculateDepreciation(Convert.ToDateTime(GlobalVariable.StartedDate));
        }

        /// <summary>
        /// Handles the EditValueChanged event of the txtQuantity control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        private void txtQuantity_EditValueChanged(object sender, EventArgs e)
        {
            CalculateOrgPrice();
        }

       

        /// <summary>
        /// Handles the EditValueChanged event of the txtUnitPrice control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        private void txtUnitPrice_EditValueChanged(object sender, EventArgs e)
        {
            
            CalculateOrgPrice();
            CalculateDepreciation(Convert.ToDateTime(GlobalVariable.StartedDate));
        }

        /// <summary>
        /// Handles the EditValueChanged event of the txtOrgPrice control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        private void txtOrgPrice_EditValueChanged(object sender, EventArgs e)
        {

            CalculateDepreciation(Convert.ToDateTime(GlobalVariable.StartedDate));
        }

        /// <summary>
        /// Handles the EditValueChanged event of the txtAccumDepreciationAmount control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        private void txtAccumDepreciationAmount_EditValueChanged(object sender, EventArgs e)
        {
           
            txtRemainingAmount.Value = txtOrgPrice.Value - txtAccumDepreciationAmount.Value;
        }

        /// <summary>
        /// Handles the EditValueChanged event of the txtRemainingAmount control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        private void txtRemainingAmount_EditValueChanged(object sender, EventArgs e)
        {
            txtAccumDepreciationAmount.Value = txtOrgPrice.Value - txtRemainingAmount.Value;
        }

      

        /// <summary>
        /// Handles the EditValueChanged event of the grdLookUpDepartment control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        private void grdLookUpDepartment_EditValueChanged(object sender, EventArgs e)
        {
            //_employeesPresenter.DisplayByDepartment(DepartmentId);
        }

        /// <summary>
        /// Handles the EditValueChanged event of the dtPurchasedDate control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        private void dtPurchasedDate_EditValueChanged(object sender, EventArgs e)
        {
            dtUsedDate.DateTime = dtPurchasedDate.DateTime;
            dtDepreciationDate.DateTime = DateTime.Parse(dtPurchasedDate.DateTime.Year + 1 + "/1/1");
        }

        /// <summary>
        /// Handles the EditValueChanged event of the dtDepreciationDate control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        private void dtDepreciationDate_EditValueChanged(object sender, EventArgs e)
        {
            CalculateDepreciation(Convert.ToDateTime(GlobalVariable.SystemDate));
        }

        /// <summary>
        /// Handles the EditValueChanged event of the grdLookUpFixedAssetCategory control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        private void grdLookUpFixedAssetCategory_EditValueChanged(object sender, EventArgs e)
        {
            //txtLifeTime.Value = grdLookUpFixedAssetCategoryView.GetFocusedRowCellValue("LifeTime") != null ? (decimal)grdLookUpFixedAssetCategoryView.GetFocusedRowCellValue("LifeTime") : 0;
            txtLifeTime.Value = grdLookUpFixedAssetCategoryView.GetFocusedRowCellValue("LifeTime") != null ? (decimal)grdLookUpFixedAssetCategoryView.GetFocusedRowCellValue("LifeTime") : 0;
            txtDepreciationRate.Value = grdLookUpFixedAssetCategoryView.GetFocusedRowCellValue("DepreciationRate") != null ? (decimal)grdLookUpFixedAssetCategoryView.GetFocusedRowCellValue("DepreciationRate") : 0;
            grdLookUpDepreciationAccount.EditValue = grdLookUpFixedAssetCategoryView.GetFocusedRowCellValue("DepreciationAccountCode") ?? "";
            grdLookUpCapitalAccount.EditValue = grdLookUpFixedAssetCategoryView.GetFocusedRowCellValue("CapitalAccountCode") ?? "";
            grdLookUpOrgPriceAccount.EditValue = grdLookUpFixedAssetCategoryView.GetFocusedRowCellValue("OrgPriceAccountCode") ?? "";
        }

        /// <summary>
        /// Handles the MouseDown event of the grdLookUpFixedAssetCategoryView control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="MouseEventArgs"/> instance containing the event data.</param>
        private void grdLookUpFixedAssetCategoryView_MouseDown(object sender, MouseEventArgs e)
        {
            var view = sender as GridView;
            if (view != null)
            {
                GridHitInfo hitInfo = view.CalcHitInfo(e.Location);
                bool isParent = false;
                if (grdLookUpFixedAssetCategoryView.GetFocusedRowCellValue("IsParent") != null)
                {
                    isParent = (bool)grdLookUpFixedAssetCategoryView.GetFocusedRowCellValue("IsParent");
                }

                if (hitInfo.InRow && isParent)
                    ((DXMouseEventArgs)(e)).Handled = true;
            }
        }


        #endregion
    }
}
